package com.alcatel_lucent.scalastudy

import com.alcatel_lucent.scalastudy.model.Rational
import org.apache.commons.lang3.StringUtils.replaceEach
import java.io.{FileOutputStream, File}
import scala.io.Source.fromFile
import org.apache.commons.io.{HexDump, LineIterator, IOUtils, FileUtils}
import org.springframework.context.annotation.AnnotationConfigApplicationContext
import org.slf4j.LoggerFactory
import scala.language.implicitConversions
import org.apache.poi.xssf.usermodel.XSSFWorkbook
import org.apache.poi.ss.util.CellUtil._
import org.apache.poi.ss.util.CellRangeAddress
import org.apache.commons.lang3.{StringUtils, RandomStringUtils}
import javax.sql.DataSource


/**
 * @author Guoshun Wu
 */
object PartOne extends scala.App {
  val log = LoggerFactory.getLogger(PartOne.getClass)
  val testList = Map((1, "a"), (2, "b"))
  for((k,v)<-testList){
    println(s"$k=$v")
  }
  testList.foreach(x => {
    println(x)
  })

  //  encodingTest()
  def springTest() {
    val ctx = new AnnotationConfigApplicationContext(classOf[AppConfig])
    println(ctx.getBean("rationalBean") + ", " + ctx.getBean(classOf[Rational]))
    val ds = ctx.getBean(classOf[DataSource])
    val conn = ds.getConnection
    conn.close()

  }

  def encodingTest() {
    val encoding = "iso-8859-1"

    //  val dir = "C:\\Users\\Administrator\\Desktop"
    //  val file = new File(dir, "Other.txt")
    //  val str = FileUtils.readFileToString(file, encoding)
    //  print(str)
    //  FileUtils.write(new File(dir, "OtherTest.txt"), str, encoding)

    val src = "中T"
    val errorEncoding = "gbk"
    val srcBytes = src.getBytes(errorEncoding)
    val srcCorrect = new String(srcBytes, errorEncoding)
    val srcCommon = new String(srcBytes, encoding)
    val toBytes = srcCommon.getBytes(encoding)
    val renew = new String(toBytes, errorEncoding)
    println(s"src =${src}, srcCorrect =${srcCorrect}, srcCommon =${srcCommon}, renew=${renew}")
    println("errorEncoding =" + errorEncoding)
    println("srcBytes: ")
    HexDump.dump(srcBytes, 0, System.out, 0)
    println("srcBytes: ")
    HexDump.dump(toBytes, 0, System.out, 0)


  }

  //    rationalTest()
  //    grep(".*println.*", ".", Array("scala")).foreach(println)
  //println(multiTable())

  def filesMatching(query: String, matcher: (String, String) => Boolean) = {
    val filesHere = (new java.io.File(".")).listFiles
    for (file <- filesHere; if (matcher(file.getName, query))) yield file
  }

  def filesEnding(query: String) = filesMatching(query, _.endsWith(_))

  def fileLines(file: File) = fromFile(file).getLines

  def grep(pattern: String, path: String = ".", extensions: Array[String] = null, recursive: Boolean = true) = {
    val files = FileUtils.listFiles(new File(path), extensions, recursive).toArray(new Array[File](0))
    for {
      file <- files
      line <- fileLines(file)
      trimmed = line.trim
      if (trimmed.matches(pattern))
    } yield trimmed
  }

  def printFile() {
    val fileName = "src/main/scala/" + replaceEach(getClass.toString, Array("class ", ".", "$"), Array("", "/", ".scala"))
    fromFile(fileName).getLines.foreach(println)
  }

  def rationalTest() {
    val oneHalf = new Rational(1, 2)
    val twoThirds = new Rational(2, 3)

    println(s"${oneHalf} * ${twoThirds} = ${oneHalf * twoThirds}")
    println(new Rational(4))
    println(new Rational(45, 35))

    println(twoThirds * 3)
    println(s"reciprocal of ${twoThirds} = ${twoThirds.reciprocal}")
    println(s"${oneHalf} / ${twoThirds} = ${oneHalf / twoThirds}")
    println(s"${oneHalf} / ${2} = ${oneHalf / 2}")

    implicit def intToRational(x: Int) = new Rational(x)

    println(s"${2} / ${oneHalf} = ${2 / oneHalf}")
  }

  // Returns a raw as a string
  def makeRow(row: Int) = (for (col <- 1 to row) yield {
    "%4d".format(row * col)
  }).mkString

  // Returns table as a string with one row per line
  def multiTable(rowNumber: Int = 9) = (for (row <- 1 to rowNumber) yield makeRow(row)).mkString("\n")

  def apachePOITest() {
    val wb = new XSSFWorkbook()
    //Workbook wb = new XSSFWorkbook()
    val createHelper = wb.getCreationHelper()
    val sheet = wb.createSheet("new sheet")



    // Create a row and put some cells in it. Rows are 0 based.
    val row = sheet.createRow(0)
    // Create a cell and put a value in it.
    createCell(row, 0, "=34+56+NOW()*0")

    // Or do it on one line.
    row.createCell(1).setCellValue(1.2)
    row.createCell(2).setCellValue(createHelper.createRichTextString("This is a string"))
    createCell(row, 0, "Hello, this is world")
    row.createCell(3).setCellValue(true)
    createCell(row, 4, "Hi, I am merged")

    sheet.addMergedRegion(new CellRangeAddress(row.getRowNum, row.getRowNum, 4, 10))
    createCell(row, 11, "after ranged.")

    //
    val row1 = sheet.createRow(1)

    for (i <- 0 to 4) {
      createCell(row1, i, RandomStringUtils.randomAlphanumeric(10))
    }

    createCell(row1, 11, RandomStringUtils.randomAlphanumeric(12))

    sheet.setAutobreaks(true)

    //    var autoFilterRange = CellRangeAddress.valueOf("A1:L1")
    val autoFilterRange = sheet.getMergedRegion(0)
    println("Auto filter range=" + autoFilterRange)
    sheet.setAutoFilter(autoFilterRange)

    val fileOut = new FileOutputStream("workbook.xlsx")

    wb.write(fileOut)

    println("*")
    fileOut.close()
  }
}
